package com.gagakuai.bpm.config.security;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;


/*
 * 自动知会
 */

@Slf4j
@Component
public class AutoInformService implements JavaDelegate {

    @Override
    public void execute(DelegateExecution execution) throws Exception {
        try{
            // 如果是知会多个人 以 ，隔开
            Object assignees = execution.getVariable("assignee");
            Object executionId = execution.getVariable("executionId");
            if(ObjectUtils.isEmpty(executionId)){
                log.info("executionId: 值不能为空");
                return;
            }

            if(ObjectUtils.isNotEmpty(assignees)){
                String assigneeStr = assignees.toString().trim();
                String[] assigneeArray = assigneeStr.split(",");
                for (String assignee : assigneeArray){
                    TaskEntity taskEntity = new TaskEntity();
                    taskEntity.setId(UUID.randomUUID().toString());
                    taskEntity.setRevision(1);
                    taskEntity.setExecutionId(executionId.toString());
                    taskEntity.setProcessInstanceId(execution.getProcessInstanceId());
                    taskEntity.setProcessDefinitionId(execution.getProcessDefinitionId());
                    taskEntity.setName(execution.getCurrentActivityName());
                    taskEntity.setParentTaskId("自动知会");
                    taskEntity.setDescription("自动知会");
                    taskEntity.setTaskDefinitionKey(execution.getCurrentActivityId());
                    taskEntity.setPriority(50);
                    taskEntity.setCreateTime(new Date());
                    taskEntity.setSuspensionState(1);
                    taskEntity.setAssignee(assignee.trim());
                    taskEntity.insert();
                }
            }
        }catch (Exception e){
            throw new Exception("自动知会 异常 ", e);
        }
    }
}
